package DataStructure.sort.innerSort.innerSortImpl;

import Logic.utils.UTFactory;
import Top100.basicDS.SortInterface;
import org.junit.Test;

/**
 * @author liujun
 * @version 1.0
 * @date 2020/6/21
 * @author—Email ljfirst@mail.ustc.edu.cn
 * @blogURL https://blog.csdn.net/ljfirst
 * @description 堆排序
 */
public class HeapSort2 implements SortInterface {

    @Test // 点击运行测试案例
    public void test() throws Exception {
        UTFactory.test(this.getClass().getName());
    }

    @Override
    public void sortMethod(int[] array) {
        //输入检查
        if (!check(array)) {
            return;
        }
        int length = array.length - 1;
        for (int i = 0; i < length; i++) {
            heapify_big(array, length - i);
            swap(array, 0, length - i);
        }
    }

    //小顶堆
    public void heapify_big(int[] array, int border) {

        //见tips001
        for (int root = (border - 1) / 2; root >= 0; root--) {
            int child = 2 * root + 1;
            // tips002:边界值的等于需要特别注意
            if (child + 1 <= border) {
                child = array[child] > array[child + 1] ? child : child + 1;
            }
            if (child <= border && array[child] > array[root]) {
                swap(array, child, root);
            }
        }
    }
}
